/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.core.provider.transport;

import com.lvyh.lightframe.common.util.CommonUtils;
import com.lvyh.lightframe.core.cache.ServiceRegistryCache;
import com.lvyh.lightframe.common.RpcContext;
import com.lvyh.lightframe.common.ext.ExtensionLoaderFactory;
import com.lvyh.lightframe.core.annotation.Service;
import com.lvyh.lightframe.common.util.NetUtil;
import com.lvyh.lightframe.common.exception.RpcRuntimeException;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.CollectionUtils;

import java.util.Map;

@Data
public class ProviderBootstrapManager implements ApplicationContextAware, InitializingBean, DisposableBean {

    private static final Logger logger = LoggerFactory.getLogger(ProviderBootstrapManager.class);

    private Class<? extends ProviderBootstrap> providerBootstrap = null;

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {

        Map<String, Object> serviceBeanMap = ctx.getBeansWithAnnotation(Service.class);
        if (!CollectionUtils.isEmpty(serviceBeanMap)) {
            for (Object serviceBean : serviceBeanMap.values()) {
                Service rpcService = serviceBean.getClass().getAnnotation(Service.class);
                String serviceName = rpcService.value().getName();
                String serviceVersion = rpcService.version();
                String serviceUniqueCode = CommonUtils.buildServiceUniqueCode(serviceName, serviceVersion);
                ServiceRegistryCache.put(serviceUniqueCode, serviceBean);
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (NetUtil.isPortUsed(RpcContext.getPort())) {
            throw new RpcRuntimeException("provider port[" + RpcContext.getPort() + "] is used.");
        }

        ProviderBootstrap providerBootstrap = ExtensionLoaderFactory.getExtensionLoader(ProviderBootstrap.class).getExtension(RpcContext.getTransport());
        providerBootstrap.startup();
    }

    @Override
    public void destroy() throws Exception {
        ProviderBootstrap providerBootstrap = ExtensionLoaderFactory.getExtensionLoader(ProviderBootstrap.class).getExtension(RpcContext.getTransport());
        providerBootstrap.stop();
    }

}
